#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request, error, redirect
from include import ip

def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/idc')
class IDC(object):

    #def __begin__(self):
        #"""
        #用户验证
        #"""
        #from uliweb import functions
        #return functions.require_login()

    def __init__(self):
        from uliweb.orm import get_model
        self.regionmodel = get_model('region')
        self.regionprovincemodel = get_model('regionprovince')
        self.regioncitymodel = get_model('regioncity')
        self.regionareamodel = get_model('regionarea')
        self.view_regionmodel = get_model('view_region')
        self.networkbusinessmodel = get_model('networkbusiness')
        self.computerroommodel = get_model('computerroom')
        self.rackspacemodel = get_model('rackspace')
        self.ippoolmodel = get_model('ippool')
        self.servermodel = get_model('server')
        self.ipaddrmodel = get_model('ipaddress')

    def _get_region(self, id):
        _data = self.regionmodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_networkbusiness(self, id):
        _data = self.networkbusinessmodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_computerroom(self, id):
        _data = self.computerroommodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_rackspace(self, id):
        _data = self.rackspacemodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_ippool(self, id):
        _data = self.ippoolmodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_server(self, id):
        _data = self.servermodel.get(int(id))
        if not _data:
            return None
        return _data    

    def region(self):
        """
        区域信息
        """
        return {}    

    def regionadd(self):
        """
        添加区域
        """
        return {}

    def regiondel(self):
        """
        删除区域信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        #self.regionmodel.filter(self.regionmodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)

    def regionedit(self):
        """
        编辑区域信息
        """
        _id = request.GET.get("id")
        return {}

    def regionsave(self):
        """
        保存地区信息
        """
        _id = request.POST.get('id')
        region_code= request.POST.get('region_code')
        region_name = request.POST.get('region_name')

        if _id == None:
            ormdata = self.regionmodel(region_code=region_code,
                                       region_name=region_name
                                       )
        else:
            ormdata = self._get_region(_id)

            ormdata.region_code=region_code
            ormdata.region_name=region_name

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"地区已经存在"})



    def networkbusiness(self):
        """
        运营商信息
        """
        return {}    

    def networkbusinessadd(self):
        """
        添加运营商
        """
        return {}

    def networkbusinessdel(self):
        """
        删除运营商信息
        """
        _id = request.POST.get('id')

        #保存删除id
        mid = []
        #保存不允许删除id
        del_fail = []
        for i in _id.split(','):
            #检查,是否包含关联
            _data = self.computerroommodel.filter(self.computerroommodel.c.networkbusiness_id == int(i)).count()
            if _data == 0:
                mid.append(int(i))
            else:
                del_fail.append(int(i))


        #一次删除多个
        if len(mid) != 0:
            self.networkbusinessmodel.filter(self.networkbusinessmodel.c.id.in_(mid)).remove()

        del_fail_name = []
        if len(del_fail) != 0:
            ormdata = self.networkbusinessmodel.filter(self.networkbusinessmodel.c.id.in_(del_fail))

            for i in ormdata:
                del_fail_name.append(i.networkbusiness_name)

        if len(del_fail_name) != 0:
            msg = ",".join(del_fail_name).encode('utf8') + " 包含关联数据,不允许删除"
            d = {"status":"200","msg":msg}
        else:
            d = {"status":"200","msg":"删除成功"}
        return json(d)

    def networkbusinessedit(self):
        """
        编辑运营商信息
        """
        _id = request.GET.get('id')
        
        return {}

    def networkbusinesssave(self):
        """
        保存运营商信息
        """
        _id = request.POST.get('id')
        networkbusiness_name= request.POST.get('networkbusiness_name')

        if _id == None:
            ormdata = self.networkbusinessmodel(networkbusiness_name=networkbusiness_name)
        else:
            ormdata = self._get_networkbusiness(_id)

            ormdata.networkbusiness_name=networkbusiness_name

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"运营商已经存在"})


    def computerroom(self):
        """
        机房信息
        """
        return {}    

    def computerroomadd(self):
        """
        添加机房
        """
        return {}

    def computerroomedit(self):
        """
        编辑机房
        """
        _id = request.GET.get('id')
        ormdata = self._get_computerroom(_id)

        return {'networkbusiness_id':ormdata.networkbusiness_id.id,
                'province_id':ormdata.province_id.id,
                'city_id':ormdata.city_id.id,
                'area_id':ormdata.area_id.id,
                'cr_address':ormdata.cr_address}        


    def computerroomsave(self):
        """
        保存机房信息
        """
        _id = request.POST.get('id')
        networkbusiness_id= request.POST.get('networkbusiness_id')
        cr_name = request.POST.get('cr_name')
        cr_level = request.POST.get('cr_level')
        cr_phone = request.POST.get('cr_phone')
        cr_tech_linkname = request.POST.get('cr_tech_linkname')
        cr_tech_phone = request.POST.get('cr_tech_phone')
        cr_chat_tools = request.POST.get('cr_chat_tools')
        cr_sales = request.POST.get('cr_sales')
        cr_sales_phone = request.POST.get('cr_sales_phone')
        cr_sales_mobile = request.POST.get('cr_sales_mobile')
        cr_sales_email = request.POST.get('cr_sales_email')
        province_id = request.POST.get('province_id')
        city_id = request.POST.get('city_id')
        area_id = request.POST.get('area_id')
        cr_address = request.POST.get('cr_address')
        comment = request.POST.get('comment')

        if _id == None:
            ormdata = self.computerroommodel(networkbusiness_id=networkbusiness_id,
                                             cr_name=cr_name,
                                             cr_level=cr_level,
                                             cr_phone=cr_phone,
                                             cr_tech_linkname=cr_tech_linkname,
                                             cr_tech_phone=cr_tech_phone,
                                             cr_chat_tools=cr_chat_tools,
                                             cr_sales=cr_sales,
                                             cr_sales_phone=cr_sales_phone,
                                             cr_sales_mobile=cr_sales_mobile,
                                             cr_sales_email=cr_sales_email,
                                             province_id=province_id,
                                             city_id=city_id,
                                             area_id=area_id,
                                             cr_address=cr_address,
                                             comment=comment
                                             )
        else:
            ormdata = self._get_computerroom(_id)

            ormdata.networkbusiness_id=networkbusiness_id
            ormdata.cr_name=cr_name
            ormdata.cr_level=cr_level
            ormdata.cr_phone=cr_phone
            ormdata.cr_tech_linkname=cr_tech_linkname
            ormdata.cr_tech_phone=cr_tech_phone
            ormdata.cr_chat_tools=cr_chat_tools
            ormdata.cr_sales=cr_sales
            ormdata.cr_sales_phone=cr_sales_phone
            ormdata.cr_sales_mobile=cr_sales_mobile
            ormdata.cr_sales_email=cr_sales_email
            ormdata.province_id=province_id
            ormdata.city_id=city_id
            ormdata.area_id=area_id
            ormdata.cr_address=cr_address
            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"机房已经存在"})

    def computerroomdel(self):
        """
        删除机房信息
        """
        _id = request.POST.get('id')

        #保存删除id
        mid = []
        #保存不允许删除id
        del_fail = []
        for i in _id.split(','):
            #检查机柜,是否包含关联
            rackspace = self.rackspacemodel.filter(self.rackspacemodel.c.computerroom_id == int(i)).count()
            if rackspace == 0:
                mid.append(int(i))
            else:
                del_fail.append(int(i))


        #一次删除多个
        if len(mid) != 0:
            self.computerroommodel.filter(self.computerroommodel.c.id.in_(mid)).remove()

        del_fail_name = []
        if len(del_fail) != 0:
            ormdata = self.computerroommodel.filter(self.computerroommodel.c.id.in_(del_fail))

            for i in ormdata:
                del_fail_name.append(i.cr_name)

        if len(del_fail_name) != 0:
            msg = ",".join(del_fail_name).encode('utf8') + " 包含关联数据,不允许删除"
            d = {"status":"200","msg":msg}
        else:
            d = {"status":"200","msg":"删除成功"}
        return json(d)


    def rackspace(self):
        """
        机柜信息
        """
        return {}    

    def rackspaceadd(self):
        """
        添加机柜信息
        """
        return {}


    def rackspaceedit(self):
        """
        编辑机柜信息
        """

        _id = request.GET.get('id')
        #ormdata = self._get_rackspace(id)
        ormdata = functions.get_object(self.rackspacemodel, _id, cache=True)

        print ormdata

        return {'cr_name':ormdata.computerroom_id.id}        


    def rackspacesave(self):
        """
        保存机柜信息
        """
        _id = request.POST.get('id')
        rackspace_name= request.POST.get('rackspace_name').strip()
        computerroom_id = request.POST.get('computerroom_id')
        comment = request.POST.get('comment')

        if _id == None:

            #检查是否存在同机房同机柜存在
            count = self.rackspacemodel.filter(self.rackspacemodel.c.rackspace_name == rackspace_name).filter(self.rackspacemodel.c.computerroom_id == computerroom_id).count()

            if count != 0:
                return json({"error":500,"msg":"在当前机房已经存在相同的机柜"})

            ormdata = self.rackspacemodel(rackspace_name=rackspace_name,
                                          computerroom_id=computerroom_id,
                                          comment=comment
                                          )
        else:
            #ormdata = self._get_rackspace(_id)

            #使用redis 的方式进行处理
            ormdata = functions.get_object(self.rackspacemodel, _id, cache=True)
            ormdata.rackspace_name=rackspace_name
            ormdata.computerroom_id=computerroom_id
            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"添加失败"})

    def rackspacedel(self):
        """
        删除机柜信息
        """
        _id = request.POST.get('id')

        #保存删除id
        mid = []
        #保存不允许删除id
        del_fail = []
        for i in _id.split(','):
            #检查机柜,是否包含关联
            _data = self.servermodel.filter(self.servermodel.c.rackspace_id == int(i)).count()
            if _data == 0:
                mid.append(int(i))
            else:
                del_fail.append(int(i))


        #一次删除多个
        if len(mid) != 0:
            self.rackspacemodel.filter(self.rackspacemodel.c.id.in_(mid)).remove()

        del_fail_name = []
        if len(del_fail) != 0:
            ormdata = self.rackspacemodel.filter(self.rackspacemodel.c.id.in_(del_fail))

            for i in ormdata:
                del_fail_name.append(i.rackspace_name)

        if len(del_fail_name) != 0:
            msg = ",".join(del_fail_name).encode('utf8') + " 包含关联数据,不允许删除"
            d = {"status":"200","msg":msg}
        else:
            d = {"status":"200","msg":"删除成功"}
        return json(d)


    def ippool(self):
        """
        IP地址池信息
        """
        return {}    

    def ippooladd(self):
        """
        添加IP地址池信息
        """
        return {}


    def ippooledit(self):
        """
        编辑IP地址池信息
        """

        _id = request.GET.get('id')
        #ormdata = self._get_rackspace(id)
        ormdata = functions.get_object(self.rackspacemodel, _id, cache=True)

        return {'cr_name':ormdata.computerroom_id.id}        


    def ippoolsave(self):
        """
        保存IP地址池信息
        """
        _id = request.POST.get('id')
        ippool_prefix= request.POST.get('ippool_prefix')
        ippool_gateway= request.POST.get('ippool_gateway')
        computerroom_id = request.POST.get('computerroom_id')
        comment = request.POST.get('comment')

        if not ip.ip_check(ippool_prefix):
            return json({"error":500,"msg":"IP地址池填写错误"})

        if not ip.ip_checksame_net(ippool_gateway,ippool_prefix):
            return json({"error":500,"msg":"网关不在该IP网段中"})

        if _id == None:

            #检查是否存在同机房同机柜存在
            count = self.ippoolmodel.filter(self.ippoolmodel.c.ippool_prefix == ippool_prefix).filter(self.ippoolmodel.c.computerroom_id == computerroom_id).count()

            if count != 0:
                return json({"error":500,"msg":"在当前机房已经存在相同的IP地址池"})  

            ormdata = self.ippoolmodel(ippool_prefix=ip.ip_ip_prefix(ippool_prefix),
                                       ippool_netmask = ip.ip_netmask(ippool_prefix),
                                       ippool_len = ip.ip_len(ippool_prefix),
                                       ippool_gateway = ippool_gateway,
                                       computerroom_id=computerroom_id,
                                       comment=comment
                                       )
        else:
            ormdata = self._get_ippool(_id)

            ormdata.ippool_prefix=ippool_prefix
            ormdata.ippool_gateway=ippool_gateway
            ormdata.computerroom_id=computerroom_id
            ormdata.comment=comment

        try:
            ormdata.save()

            if _id == None:
                iplist = ip.ip_list(ippool_prefix)
                for i in iplist:
                    ipaddr = self.ipaddrmodel(ip_address = i,
                                              ippool_id = ormdata
                                              )
                    ipaddr.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"IP池已经存在"})

    def ippooldel(self):
        """
        删除IP地址池信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #保存删除id
        mid = []
        #保存不允许删除id
        del_fail = []
        for i in _id.split(','):
            #检查IP地址,是否包含关联
            _data = self.ipaddrmodel.filter(self.ipaddrmodel.c.ippool_id == int(i)).filter(self.ipaddrmodel.c.ip_status == 1).count()
            if _data == 0:
                mid.append(int(i))
            else:
                del_fail.append(int(i))


        #一次删除多个
        if len(mid) != 0:
            self.ipaddrmodel.filter(self.ipaddrmodel.c.ippool_id.in_(mid)).remove()
            self.ippoolmodel.filter(self.ippoolmodel.c.id.in_(mid)).remove()
            

        del_fail_name = []
        if len(del_fail) != 0:
            ormdata = self.ippoolmodel.filter(self.ippoolmodel.c.id.in_(del_fail))

            for i in ormdata:
                del_fail_name.append(i.ippool_prefix)

        if len(del_fail_name) != 0:
            msg = ",".join(del_fail_name).encode('utf8') + " 包含关联数据,不允许删除"
            d = {"status":"200","msg":msg}
        else:
            d = {"status":"200","msg":"删除成功"}
        return json(d)

    def ippooldetail(self):
        """
        查看IP地址明细
        """
        _id = request.GET.get('id')
        ormdata = self._get_ippool(_id)
        return {'ipaddrs':ormdata.pool.all()}
    
    